package com.tosh;

import com.tosh.model.Bean;

import javax.xml.stream.XMLStreamException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * User: arsentyev
 * Date: 31.07.12
 */
public class AppFastDI {
    private final static Logger _log = Logger.getLogger(AppFastDI.class.getName());
    private final static Map<String, Object> beansMap = new HashMap<String, Object>();

    private AppFastDI() {/*empty*/}

    public AppFastDI(File configFile) {
        build(configFile);
    }

    public AppFastDI(String configName) {
        build(configName);
    }

    public AppFastDI(InputStream configFileStream) {
        build(configFileStream);
    }

    public AppFastDI(ClassPathResource cpr) {
        build(cpr);
    }

    private void build(File configFile) {
        try {
            build(new FileInputStream(configFile));
        } catch (IOException e) {
            _log.log(Level.SEVERE, null, e);
        }
    }

    private void build(ClassPathResource cpr) {
        try {
            build(cpr.getInputStream());
        } catch (IOException e) {
            _log.log(Level.SEVERE, null, e);
        }
    }

    public void build(String configName) {
        try {
            build(new ClassPathResource(configName).getInputStream());
        } catch (IOException e) {
            _log.severe(e.getMessage());
        }
    }

    private void build(InputStream is) {
        XmlBeanFactory factory = new XmlBeanFactory(is);

        try {
            List<Bean> beans = factory.getBeans();

            ResolverFastDI.fillByInstances(beans, beansMap);

            ResolverFastDI.resolveDependencies(beans, beansMap);
        } catch (ClassNotFoundException e) {
            _log.log(Level.SEVERE, null, e);
        } catch (InstantiationException e) {
            _log.log(Level.SEVERE, null, e);
        } catch (IllegalAccessException e) {
            _log.log(Level.SEVERE, null, e);
        } catch (XMLStreamException e) {
            _log.log(Level.SEVERE, null, e);
        } catch (NoSuchMethodException e) {
            _log.log(Level.SEVERE, null, e);
        } catch (InvocationTargetException e) {
            _log.log(Level.SEVERE, null, e);
        }
    }

    public Object getBean(String key) {
        return beansMap.get(key);
    }
}